package cn.yh.register.oss.service.impl;

import cn.yh.register.oss.service.FileService;
import cn.yh.register.oss.utils.ConstantOssPropertiesUtils;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.OSSClientBuilder;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@Service
public class FileServiceImpl implements FileService {
    /**
     * 文件上传
     *
     * @param file 文件对象
     * @return 文件的地址
     */
    @Override
    public String upload(MultipartFile file) {

        OSS ossClient = new OSSClientBuilder().build(ConstantOssPropertiesUtils.EDNPOINT,
                ConstantOssPropertiesUtils.ACCESS_KEY_ID,
                ConstantOssPropertiesUtils.SECRECT);
        //获取原始的文件名
        String fileName = file.getOriginalFilename();
        if (!StringUtils.isEmpty(fileName)) {
            //拼接新的文件名
            //截取的扩展名
            String ext = fileName.substring(fileName.lastIndexOf("."));
            //拼接新的文件名  日期作为文件目录
            String dateStr = new DateTime().toString("yyyy/MM/dd");
            //拼接
            fileName = dateStr + "/" + System.currentTimeMillis()+ ext;
        }

        //上传
        try {
            ossClient.putObject(ConstantOssPropertiesUtils.BUCKET,fileName,file.getInputStream());
            //返回文件的网络地址
            return "https://"+ConstantOssPropertiesUtils.BUCKET+"."+ConstantOssPropertiesUtils.EDNPOINT+"/"+fileName;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
